<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="后勤设备" prop="equipmentId">
        <Aselect
          :options="equipmentList"
          v-model="queryParams.equipmentId"
          filterable
        ></Aselect>
      </el-form-item>
      <el-form-item label="故障类型" prop="faultType">
        <el-select
          v-model="queryParams.faultType"
          placeholder="请选择故障类型"
          clearable
        >
          <el-option
            v-for="dict in equipment_fault_type_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报修人" prop="reporter">
        <el-input
          v-model="queryParams.reporter"
          placeholder="请输入报修人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报修时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeReportTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="维修状态" prop="repairStatus">
        <el-select
          v-model="queryParams.repairStatus"
          placeholder="请选择维修状态"
          clearable
        >
          <el-option
            v-for="dict in equipment_repair_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修负责人" prop="repairPerson">
        <el-input
          v-model="queryParams.repairPerson"
          placeholder="请输入维修负责人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['repair:repair:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['repair:repair:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['repair:repair:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['repair:repair:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="repairList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="维修单号"
        align="center"
        prop="repairId"
        width="100"
      />
      <el-table-column
        label="设备名称"
        align="center"
        prop="equipmentId"
      >
        <template #default="scope">
          {{
            equipmentList.find(
              (item) => item.value == scope.row.equipmentId
            )?.label
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="故障类型"
        align="center"
        prop="faultType"
        width="100"
      >
        <template #default="scope">
          <dict-tag
            :options="equipment_fault_type_status"
            :value="scope.row.faultType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="设备图片"
        align="center"
        prop="equipmentImg"
        width="100"
      >
        <template #default="scope">
          <image-preview
            :src="scope.row.equipmentImg"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="报修人"
        align="center"
        prop="reporter"
      />
      <el-table-column
        label="维修状态"
        align="center"
        prop="repairStatus"
      >
        <template #default="scope">
          <dict-tag
            :options="equipment_repair_status"
            :value="scope.row.repairStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="维修负责人"
        align="center"
        prop="repairPerson"
        width="100"
      />
      <el-table-column
        label="报修时间"
        align="center"
        prop="reportTime"
        width="150"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.reportTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始维修时间"
        align="center"
        prop="startTime"
        width="150"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.startTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="完成时间"
        align="center"
        prop="completeTime"
        width="150"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.completeTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="故障描述"
        align="center"
        prop="faultDescription"
        width="250"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['repair:repair:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['repair:repair:remove']"
            v-if="
              scope.row.repairStatus == 3 ||
              scope.row.repairStatus == 4
            "
            >删除</el-button
          >
          <el-button
            link
            type="danger"
            icon="Close"
            @click="repairEquipmentBtn(scope.row)"
            v-hasPermi="['repair:repair:remove']"
            v-if="
              scope.row.repairStatus == 1 ||
              scope.row.repairStatus == 2
            "
            >撤回修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备维修记录对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="repairRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="后勤设备" prop="equipmentId">
          <Aselect
            :options="equipmentList"
            v-model="form.equipmentId"
            filterable
          ></Aselect>
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select
            v-model="form.faultType"
            placeholder="请选择故障类型"
          >
            <el-option
              v-for="dict in equipment_fault_type_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报修人" prop="reporter">
          <el-input
            v-model="form.reporter"
            placeholder="请输入报修人"
          />
        </el-form-item>
        <el-form-item
          label="维修负责人"
          prop="repairPerson"
        >
          <el-input
            v-model="form.repairPerson"
            placeholder="请输入维修负责人"
          />
        </el-form-item>
        <el-form-item
          label="故障描述"
          prop="faultDescription"
        >
          <el-input
            v-model="form.faultDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="设备图片" prop="equipmentImg">
          <image-upload v-model="form.equipmentImg" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Repair">
import {
  listRepair,
  getRepair,
  delRepair,
  addRepair,
  updateRepair,
  repairEquipment
} from "@/api/repair/repair";
import { listEquipment } from "@/api/equipment/equipment";
import Aselect from "@/components/Select/Aselect.vue";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
const {
  equipment_fault_type_status,
  equipment_repair_status
} = proxy.useDict(
  "equipment_fault_type_status",
  "equipment_repair_status"
);

const repairList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeReportTime = ref([]);
const daterangeStartTime = ref([]);
const daterangeCompleteTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentId: null,
    faultType: null,
    faultDescription: null,
    reporter: null,
    reportTime: null,
    repairStatus: null,
    repairPerson: null,
    startTime: null,
    completeTime: null,
    repairCost: null,
    solution: null,
    partsReplaced: null,
    repairNotes: null,
    equipmentImg: null
  },
  rules: {
    repairId: [
      {
        required: true,
        message: "维修单号不能为空",
        trigger: "blur"
      }
    ],
    equipmentId: [
      {
        required: true,
        message: "设备ID不能为空",
        trigger: "blur"
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  getEquipmentList();
});

// 设备
const equipmentList = ref([]);
function getEquipmentList() {
  listEquipment({
    pageNum: 1,
    pageSize: 100
  }).then((response) => {
    equipmentList.value = response.rows.map((res) => {
      return {
        value: res.equipmentId,
        label: res.name
      };
    });
    console.log(equipmentList.value);
  });
}

/** 查询设备维修记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (
    null != daterangeReportTime &&
    "" != daterangeReportTime
  ) {
    queryParams.value.params["beginReportTime"] =
      daterangeReportTime.value[0];
    queryParams.value.params["endReportTime"] =
      daterangeReportTime.value[1];
  }
  if (
    null != daterangeStartTime &&
    "" != daterangeStartTime
  ) {
    queryParams.value.params["beginStartTime"] =
      daterangeStartTime.value[0];
    queryParams.value.params["endStartTime"] =
      daterangeStartTime.value[1];
  }
  if (
    null != daterangeCompleteTime &&
    "" != daterangeCompleteTime
  ) {
    queryParams.value.params["beginCompleteTime"] =
      daterangeCompleteTime.value[0];
    queryParams.value.params["endCompleteTime"] =
      daterangeCompleteTime.value[1];
  }
  listRepair(queryParams.value).then((response) => {
    repairList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    repairId: null,
    equipmentId: null,
    faultType: null,
    faultDescription: null,
    reporter: null,
    reportTime: null,
    repairStatus: null,
    repairPerson: null,
    startTime: null,
    completeTime: null,
    repairCost: null,
    solution: null,
    partsReplaced: null,
    repairNotes: null,
    equipmentImg: null
  };
  proxy.resetForm("repairRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeReportTime.value = [];
  daterangeStartTime.value = [];
  daterangeCompleteTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.repairId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备维修记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _repairId = row.repairId || ids.value;
  getRepair(_repairId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备维修记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["repairRef"].validate((valid) => {
    if (valid) {
      if (form.value.repairId != null) {
        updateRepair(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRepair(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _repairIds = row.repairId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除设备维修记录编号为"' +
        row.name +
        '"的数据项？'
    )
    .then(function () {
      return delRepair(_repairIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 删除按钮操作 */
function repairEquipmentBtn(row) {
  const _repairIds = row.repairId || ids.value;
  proxy.$modal
    .confirm(
      '是否撤回报修设备"' +
        equipmentList.value.find(
          (item) => item.value == row.equipmentId
        )?.label
    )
    .then(function () {
      repairEquipment({
        ...row,
        repairStatus: "3"
      }).then(() => {
        proxy.$modal.msgSuccess("撤回报修成功");
        getList();
      });
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "repair/repair/export",
    {
      ...queryParams.value
    },
    `repair_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
